<?php
declare (strict_types = 1);

namespace app\block\controller;

use app\BaseController;
use think\facade\Env;
use think\facade\Db;
use app\nizw\Help;
use think\facade\Log;



class Index extends BaseController
{
    protected $BloclDB;
    protected $DBName = "mysql_block";

    public function index()
    {
        // //登入游戏
        // $data=['game'=>'吃吃碰碰'
    
        // ];
        // return json($data);
    
        // return Help::Inst2()->TestTu();
        // $data = ['name' => 'ThinkPHP'];
        // return $this->fetch('ECharts/index.html');

        $data=['game'=>'吃吃碰碰'
    
        ];
        return json($data);
    }

    public function moqi()
    {
        $data = Help::Inst($this->DBName)->Select("user");
        // dump($data);
        // return 
        // 模拟数据获取
        // echo "ssss";
        // $data = ['name' => '张三', 'age' => 30];

        // $data10=[];
        // for ($i = 0; $i < 5; $i++) {
        //     $data10[$i] = $data[$i];
        // }

        return json($data); // 使用json方法返回JSON格式数据
    }


    ///默认数据
    public function GetDefaultUser(){
        $User = [
            'name' => "",
            'avater' => "",
            'shi' => "",
            'level'=>0,
            'level2'=>0,
            'money'=>0,
            'skill1'=>0,
            'skill2'=>0,
            'skill3'=>0,
            'skill4'=>0,
            'skill5'=>0,
            'skill11'=>0,
            'time'=>time(),
        ];
        return $User;
    }


    ///数据库插入
    public function DBInsert($InsertTable,$Name){
        $row = $this->GetDB() ->name($Name) -> insertGetId($InsertTable);
        return $row;
    }

    ///数据库查询
    public function DBSelect($whereTable,$Name){
        return $this->GetDB() ->name($Name)->where($whereTable)->select();
    }

    public function DBSelect_For_UId($openId,$Name){
        $whereTable = [
            'openId'=>['eq',$openId]
        ];
        return  $this->DBSelect($whereTable,$Name);
    }
    public function DBSelect_For_Id($id,$Name){
        $whereTable = [
            'id'=>['eq',$id]
        ];
        return  $this->DBSelect($whereTable,$Name);
    }

    public function DBSelectAll($Name){
        return $this->GetDB() ->name($Name)->select();
    }


    public function GetDB(){
        if($this->BloclDB==false){
            $this ->BloclDB = DB::connect($this->DBName);
        }
        return $this->BloclDB;
    }

    public function Login($openId){
        // if()
        if($openId==''){
            $res['Users']=[];
            return json($res);
        }

        //
        $User  = $this-> DBSelect_For_UId($openId,"user");
        if(count($User)==0){

            $register = $this ->RegisterAndRefresh($openId,0,0,0,
            0,0,0,0,0,
            0,$name,$avater);
            //新增
            // return $register;
            $User  = $this-> DBSelect_For_UId($openId,"user");
        }

        // $UserAll = $this->DBSelectAll("user");
        $res['Users']=$User;
        return json($res);
    }

    public function RewardSkill($openId,
    $id1="",$c1=0,$id2="",$c2=0,
    $id3="",$c3=0,$id4="",$c4=0,$id5="",$c5=0,
    $id11="",$c11=0,
    $money=-1,$level=0,$level2=0,
    $name="",$avater="",$shi=""
    ){
        $data;

        if($id1!=""){
            $data[$id1] = $c1;
        }
        if($id2!=""){
            $data[$id2] = $c2;
        }
        if($id3!=""){
            $data[$id3] = $c3;
        }
        if($id4!=""){
            $data[$id4] = $c4;
        }
        if($id11!=""){
            $data[$id11] = $c11;
        }
        if($money!=-1){
            $data["money"] = $money;
        }
        if($level!=0){
            $data["level"] = $level;
            $check = $this->GetDB()-> name("user")->where("openId",$openId) -> select();
            if($check[0]["level"]>$level){
                $res2=[
                    "Result",0
                ];
                return json($res2);
            }
        }
        if($level2!=0){
            $data["level2"] = $level2;
        }
        if($avater!=""){
            $data["avater"] = $avater;
        }
        if($shi!=""){
            $data["shi"] = $shi;
        }
        // $User  = $this-> DBSelect_For_UId($openId,"user");
        $r = $this->GetDB()-> name("user")->where("openId",$openId) ->update($data);

        $res=[
            "Result",$r
        ];
        return json($res);
    }


    public function GetData($openId){
        $r = $this->GetDB()-> name("user")->where("openId",$openId) ->select();

        $res=[
            "Users"=>$r
        ];

        return json($res);
    }

    public function Register($openId){
        //新增
        $dUser = $this-> GetDefaultUser();
        $dUser["openId"]=$openId;
        
        $id = $this-> DBInsert( $dUser,"user");

        // $UserAll = $this->DBSelectAll("user");

        $res['Result']=$id;
        return json($res);
    }

    public function RegisterAndRefresh($openId,
    $level=0,$level2=0,$money=0,
    $skill1=0,$skill2=0,$skill3=0,$skill4=0,$skill5=0,
    $skill11=0,$name="Player",$avater="",$shi="China"
    ){
        $data=[
            'openId'=>$openId,
            'level'=>$level,
            'level2'=>$level2,
            'money'=>$money,
            'skill1'=>$skill1,
            'skill2'=>$skill2,
            'skill3'=>$skill3,
            'skill4'=>$skill4,
            'skill5'=>$skill5,
            'skill11'=>$skill11,
            'time' => time(),
        ];

        if($name!=""){
            $data["name"]=$name;
        }
        if($avater!=""){
            $data["avater"]=$avater;
        }

        if($shi!=""){
            $data["shi"]=$shi;
        }else{
            $data["shi"]="China";
        }



        $User  = $this-> DBSelect_For_UId($openId,"user");
        if(count($User)==0){
            $id = $this-> DBInsert( $data,"user");
            $User  = $this-> DBSelect_For_UId($openId,"user");
        }else{
            //$r = $this->GetDB()-> name("user")->where("openId",$openId) ->update($data);
            $res['Users']=$User;
            $res['Begin']=1;
            return json($res);
        }

        // $UserAll = $this->DBSelectAll("user");

        $res['Users']=$User;
        return json($res);
    }

    public function GetRankPart($index,$count,$selflevel){
        // $w = [
        //     'openId'=>['neq',$openId]
        // ];
        // $all =$this->GetDB() ->name("user")->where($w)->select();
        $all = $this->GetDB() ->name("user") ->order('level','desc')->select();

        // return json($all);

        $c = count($all);

        $rank=0;
        $get=false;
        for ($i = 0; $i < $c; $i++) {
            $rank=$i;
            if($all[$i]["level"]<=$selflevel){
                $get=true;
                break;
            }
        }
        if(!$get){
            $rank=$rank+1;
        }



        // $half = $count/2 +2;//补充2个
        $begin = $index-$count-2;
        $begin=max( $begin,0);

        $end = $index+$count*2+2;
        $end = min($end, $c);


        $Users=[];
        $ii=0;
        for ($i = $begin; $i < $end; $i++) {
            $Users[$ii] = $all[$i];
            $ii=$ii+1;
        }


        $res=["Users"=>$Users,"Begin"=>$begin,"End"=>$end,"All"=>$c,"Rank"=>$rank];
        return json($res);
    }

    public function ChangeIcon($openId,$name="",$avater=""){
        $data=[];

        $i=0;

        if($name!=""){
            $data["name"] = $name;
            $i=$i+1;
        }

        if($avater!=""){
            $data["avater"] = $avater;
            $i=$i+1;
        }

        $res=[];

        if($i == 0){
            $res["result"]=0;
            return json($res);
        }

        $r = $this->GetDB()-> name("user")->where("openId",$openId) ->update($data);
        $res["result"]=1;
        return json($res);
    }

    public function GetCurRank($l){
        
        $p = $l;
        if($l>0){
            $p = $l-1;
        }


        $all = $this->GetDB() ->name("user") ->order('level','desc')->select();

        // return json($all);

        $c = count($all);

        $rank=0;
        $rank2=0;
        for ($i = 0; $i < $c; $i++) {
            $rank=$i;
            if($all[$i]["level"]<=$l){
                break;
            }
        }
        for ($i = 0; $i < $c; $i++) {
            $rank2=$i;
            if($all[$i]["level"]<=$p){
                break;
            }
        }

        $res=[
            "Result"=>[
                0=> $rank2,
                1=>$rank,
            ]
        ];
        return json($res);
    }


    public function GetOpenId($appid,$secret,$js_code){
        $data=[
            'appid'=>$appid,
            'secret'=>$secret,
            'js_code'=>$js_code,
            'grant_type'=>'authorization_code',
        ];

        $url = 'https://api.weixin.qq.com/sns/jscode2session'; // 替换为你需要访问的URL
        //$url = 'https://www.baidu.com/'; // 替换为你需要访问的URL
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);


        $fromServer = json_decode($result, true); 


        //dump($fromServer);

        if(!empty($fromServer["session_key"])){

        }
        $session = $fromServer["session_key"];
        $openId = $fromServer["openid"];
        $openId = $fromServer["openid"];
 
        $res = [];
        $r = false;

        if (!empty($fromServer["session_key"])) {
            // 处理获取到的数据
            $res['session_key'] = $fromServer["session_key"];
            $r = true;
        }

        if (!empty($fromServer["openid"])) {
            $res['openid'] = $fromServer["openid"];
            $r = true;
        }

        if (!empty($fromServer["errcode"])) {
            $res['errcode'] = $fromServer["errcode"];
            $r = false;
        }
        if (!empty($fromServer["errmsg"])) {
            $res['errmsg'] = $fromServer["errmsg"];
            $r = false;
        }

        $res['Result'] = $r;

        return json($res);
    }

    public function GetCurLv($OpenId){
        $User =  $this-> DBSelect_For_UId($OpenId,"user");

        $res=[];
        $res['Users']=$User;
        return json($res);
    }

    public function FLeave($OpenId,$Level){
        $User =  $this-> DBSelect_For_UId($OpenId,"user");
        $id = $User[0]["id"];


        $whereTable = [
            'userId'=>['eq',$id]
        ];
        $l = $this->DBSelect($whereTable,"log");
        $data=[
            "time" => date("Y-m-d H:i:s"),
            "level" =>$Level,
        ];


        $res=[];
        if(count($l)==0){

            $data["userId"] = $id;
            $r = $this-> DBInsert( $data,"log");
            $res["result"]=$r;
        }
        // else{
            
        //     $r = $this->GetDB()-> name("log")->where("userId",$id) ->update($data);
        //     $res["result"]=$r;
        // }

        return json($res);
    }


    public function TestA(){
        $r = $this->GetDB()-> name("user")->select();
        $table = [];
        $all = count($r);

        for ($i = 0; $i < count($r); $i++) {

            $l = $r[$i]["level"];
            if(empty($table[$l])){
                $table[$l]=[];
                $table[$l]["count"]=1;
            }else{
                $table[$l]["count"]=$table[$l]["count"]+1;
            }
        }
        foreach($table as $k=>$v){
            $p = $v["count"]/$all;
            $table[$k]["P"] = number_format($p,4)*100;
        }

        // dump($table);

        return json($table);
    }

    public function FX(){
        Help::Inst($this->DBName)->FX_1_5firstLevel(1,5);
    }

    public function CallError($p,$Id,$Vesion){
        if(empty($Id)){
            $Id="";
        }
        // Log::error($Id."=>".$p);
        Help::Inst2()->CallError($p,$Id,$Vesion);
    }
}
